import {constantRouterMap} from 'src/router'
const _import = require('@/router/_import_development');
import Layout from '@/views/layout/Layout'

/**
 * 递归解析数据库返回menu列表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter( menus) {
    const accessedRouters = menus.filter(route => {
        if(route.component||route.isDisplay){
            if(route.component === 'Layout'){                
                route.component = Layout
                route["path"] = route.url
                route["redirect"] = 'noredirect'
            }else{
                try{
                    route.component = _import(route.component)
                    route["path"] = route.url.substring(1)     
                }catch(error){
                    return false
                }         
            }
            if(route.permissionInfos && route.permissionInfos.length){
                route["children"] = route.permissionInfos
                route.children = filterAsyncRouter(route.children)
            }
            return true
        }else{
            return false
        }
        
    });
    return accessedRouters
}

//排序方法
function sortKey(array,key){
    return array.sort(function(a,b){
        var x = a[key];
        var y = b[key];
        return ((x<y)?-1:(x>y)?1:0)
    })
}

const permission = {
    state: {
        routers: constantRouterMap,
        addRouters: []
    },
    mutations: {
        SET_ROUTERS: (state, routers) => {
            state.addRouters = routers
            state.routers = constantRouterMap.concat(routers)
        }
    },
    actions: {
        GenerateRouters({
            commit
        }, menus) {
            return new Promise(resolve => {
                const accessedRouters = filterAsyncRouter(menus);
                sortKey(accessedRouters , 'orders') //根据orders排序
                commit('SET_ROUTERS', accessedRouters);
                commit('SET_MENUS', accessedRouters);
                resolve();
            })
        }
    }
};

export default permission;
